﻿using System;
using System.Threading.Tasks;
using Casamiel.Domain;
using Casamiel.Domain.Response;
using Smooth.IoC.UnitOfWork.Interfaces;
using Dapper;
using System.Linq;
using System.Collections.Generic;

namespace Casamiel.Infrastructure.Repositories
{
	/// <summary>
	/// 
	/// </summary>
	public class MemberCouponRepository : BaseRepository<MemberCoupon, long>, IMemberCouponRepository
	{
		/// <summary>
		/// 
		/// </summary>
		/// <param name="factory"></param>
		public MemberCouponRepository(IDbFactory factory) : base(factory)
		{
		}

		/// <summary>
		/// 
		/// </summary>
		/// <typeparam name="TSession"></typeparam>
		/// <param name="OldtickectCode"></param>
		/// <returns></returns>
		public async Task<MemberCoupon> FindAsync<TSession>(string oldTicketcode) where TSession : class, ISession
		{
			using (var session = Factory.Create<TSession>()) {

				string sql = $"select top 1 * from {Sql.Table<MemberCoupon>(session.SqlDialect)} where oldTicketcode=@oldTicketcode";

				var list = await session.QuerySingleOrDefaultAsync<MemberCoupon>(sql.CheckSafeSql(), new { oldTicketcode }).ConfigureAwait(false);
				return list;
			}
		}
		/// <summary>
		/// 
		/// </summary>
		/// <typeparam name="TSession"></typeparam>
		/// <param name="tickectCode"></param>
		/// <returns></returns>
		public async Task<dynamic> GetListAsync<TSession>(string tickectCode) where TSession : class, ISession
		{
			string sql = @"select (select mobile from member where id=a.mid) as mobile, ticketCode,oldticketcode,productname,price,giveStatus,case giveStatus when 2 then '赠出' when 1 then '获赠'when - 1 then '赠送中' else '绑定' end as d,createtime from(select* from  dbo.member_coupon where   oldTicketcode=@tickectCode unionselect *FROM dbo.member_coupon where oldTicketcode in(SELECT   Ticketcode FROM dbo.member_coupon where   oldTicketcode =@tickectCode) ) as a";

			using (var session = Factory.Create<TSession>()) {
				var list = await session.QueryAsync<dynamic>(sql.CheckSafeSql(), new { tickectCode }).ConfigureAwait(false);
				return list;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <typeparam name="TSession"></typeparam>
		/// <param name="OrderCode"></param>
		/// <returns></returns>
	    public async Task<List<MemberCoupon>> GetListAsnyc<TSession>(string OrderCode) where TSession : class, ISession
		{
			using var session = Factory.Create<TSession>();
			string sql = $"select * from {Sql.Table<MemberCoupon>(session.SqlDialect)} where OrderCode=@OrderCode";

			var list = await session.QueryAsync<MemberCoupon>(sql.CheckSafeSql(), new { OrderCode }).ConfigureAwait(false);
			return list.ToList();

		}

		public async Task<List<MemberCoupon>> GetListAsnyc<TSession>(long MID, int state,DateTime UsedDate) where TSession : class, ISession
		{
			using var session = Factory.Create<TSession>();
			string sql = $"select * from {Sql.Table<MemberCoupon>(session.SqlDialect)} where MID=@MID and state=@state and UsedDate>@UsedDate";

			var list = await session.QueryAsync<MemberCoupon>(sql.CheckSafeSql(), new { MID,state,UsedDate }).ConfigureAwait(false);
			return list.ToList();

		}
		/// <summary>
		/// 
		/// </summary>
		/// <typeparam name="TSession"></typeparam>
		/// <param name="MID"></param>
		/// <param name="state">0、已使用；1、已过期；2、未启用；3、可使用</param>
		/// <param name="pageIndex"></param>
		/// <param name="pageSize"></param>
		/// <returns></returns>
		public async Task<PagingResultRsp<List<MemberCoupon>>> GetListAsnyc<TSession>(long MID, int state, int pageIndex, int pageSize) where TSession : class, ISession
		{

			using (var session = Factory.Create<TSession>()) {
				var sql = GetSelectSQL($"{Sql.Table<MemberCoupon>(session.SqlDialect)}", $" MID=@MID and state=@state and givestatus>-2", "MCID desc", pageIndex, pageSize);

				string countsql = $" select count(*) from  {Sql.Table<MemberCoupon>(session.SqlDialect)} where MID=@MID  and state=@state and givestatus>=-1";
				int total = 0;
				total = await session.QueryFirstAsync<int>(countsql, new { MID, state }).ConfigureAwait(false);
				var list = await session.QueryAsync<MemberCoupon>(sql.Item1, new { begin = sql.Item2, end = sql.Item3, MID, state }).ConfigureAwait(false);
				//var dd = from x in list
				//		 select (new MemberCouponReponse {
				//			 MID=x.MID,
				//			 MCID = x.MCID,
				//			 Productname = x.Productname,
				//			 Enddate = x.Enddate,
				//			 Price = x.Price,
				//			 Startdate = x.Startdate,
				//			 State = x.State

				//		 });
				return new PagingResultRsp<List<MemberCoupon>>(list.ToList(), pageIndex, pageSize, total, 0, "");
			}
			//var list = await session.Connection.QueryAsync<InvoiceDetail>($"SELECT * FROM {Sql.Table<InvoiceDetail>(session.SqlDialect)} where Mobile=@Mobile and CreateTime>@CreateTime", new { Mobile, CreateTime });
			//return list.ToList();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="entity"></param>
		/// <param name="GiveStatus">0可赠送；1获赠；-1赠送中；-2已赠送</param>
		/// <param name="uow"></param>
		/// <returns></returns>
		public async Task<bool> UpdateCouponGiveStatusAsnync(MemberCoupon entity, int GiveStatus, IUnitOfWork uow)
		{
            if (entity is null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            if (uow is null)
            {
                throw new ArgumentNullException(nameof(uow));
            }

			var sql = $"update {Sql.Table<MemberCoupon>(uow.SqlDialect)} set GiveStatus=@GiveStatus where MCID=@MCID and GiveStatus=@OGiveStatus";
			 
			var i = await uow.Connection.ExecuteAsync(sql.CheckSafeSql(),
				new { entity.MCID, GiveStatus, OGiveStatus = entity.GiveStatus },
				uow.Transaction)
				.ConfigureAwait(true);
			return i > 0;
		}
	}
}
